<template>
  <a-modal title-align="start" :title="props.type == 'add' ? '新增属性' : '编辑属性'" :footer="false" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="props.type == 'add' ? 600 : 1200">
    <div class="flex">
      <div style="flex: 1">
        <a-form auto-label-width ref="formRef" size="medium" :model="form">
          <template v-if="props.type == 'add'">
            <a-form-item field="name" label="名称" :rules="rules.name">
              <a-input v-model="form.name" placeholder="请输入名称" allow-clear />
            </a-form-item>
            <a-form-item field="slug" label="别名" :rules="rules.slug">
              <div style="width: 100%">
                <div> <a-input v-model="form.slug" placeholder="请输入别名" allow-clear /></div>
                <div class="common-text">建议小写字母，并且只包含字母、数字和连字符。</div>
              </div>
            </a-form-item>
          </template>
          <template v-else>
            <a-form-item field="name" label="名称" :rules="rules.name">
              <a-input v-model="form.name" placeholder="请输入名称" allow-clear />
            </a-form-item>
            <a-form-item field="slug" label="别名" :rules="rules.slug">
              <div style="width: 100%">
                <div> <a-input v-model="form.slug" placeholder="请输入别名" allow-clear /></div>
                <div class="common-text">建议小写字母，并且只包含字母、数字和连字符。</div>
              </div>
            </a-form-item>
            <a-form-item label="映射ERP属性">
              <div style="width: 100%">
                <div>
                  <a-select @change="selErpAttr" v-model="form.erpAttrId" allow-search allow-clear placeholder="请选择">
                    <a-option v-for="(item, index) of relatedList" :key="index" :value="item.id">{{ item.name }}</a-option>
                  </a-select>
                </div>
                <div class="common-text">选择erp属性，将ERP的属性值，新增到当前属性值</div>
              </div>
            </a-form-item>
          </template>
        </a-form>
        <div class="flex-c-end" style="margin-top: 30px">
          <a-button @click="showvisible = false" style="margin-right: 10px">取消</a-button>
          <a-button type="primary" :loading="loading" @click="submit">确定</a-button>
        </div>
      </div>
      <div class="table-wrap" v-if="props.type != 'add'">
        <div style="margin-bottom: 10px" class="flex-c">
          <a-input-search style="width: 240px; margin-right: 20px" placeholder="搜索" @change="changeAllPropertyValueList" @search="changeAllPropertyValueList" v-model="searchVal" />
          <a-space>
            <a-button type="outline" @click="openPropValDialog('add')">添加属性值</a-button>
            <a-button class="gray-outline" @click="deletePropVal(selectIds)">批量删除</a-button>
          </a-space>
        </div>
        <div style="flex: 1; overflow: hidden">
          <a-table row-key="id" size="mini" class="table-singe-line" @selection-change="selectColumn" :row-selection="rowSelection" :pagination="false" :data="propertyValueList" :scroll="{ x: '100%', y: '100%' }">
            <template #columns>
              <a-table-column>
                <template #title>
                  <div class="required">名称</div>
                </template>
                <template #cell="{ record }">
                  <!-- <a-input v-model="record.name" placeholder="请输入名称" allow-clear /> -->
                  <p>{{ record.name }}</p>
                </template>
              </a-table-column>
              <a-table-column>
                <template #title>
                  <div class="required">标识</div>
                </template>
                <template #cell="{ record }">
                  <!-- <a-input v-model="record.slug" placeholder="请输入标识" allow-clear /> -->
                  <p>{{ record.slug }}</p>
                </template>
              </a-table-column>
              <a-table-column title="操作" :width="80">
                <!-- <a-space style="font-size: 20px"> -->
                <template #cell="{ record }">
                  <a-space>
                    <icon-edit class="cursor ft20" @click="openPropValDialog('edit', record)" />
                    <!-- <icon-plus-circle class="cursor ft20" @click="addItem(rowIndex)" /> -->
                    <a-popconfirm content="确定是否删除?" @ok="deletePropVal([record.id])" type="error">
                      <icon-delete class="cursor ft20" />
                    </a-popconfirm>
                  </a-space>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>

        <div style="margin-top: 10px">
          <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageInfo.total" :default-page-size="pageInfo.pageSize" :current="pageInfo.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
        </div>
      </div>
    </div>
  </a-modal>
  <!-- 添加属性 -->
  <a-modal title-align="start" :title="addPropValType == 'add' ? '添加' : '编辑'" :mask-closable="false" v-model:visible="showAddPropVal" @cancel="showAddPropVal = false" :width="500">
    <a-form auto-label-width ref="propValFormRef" size="medium" style="flex: 1" :model="propValForm">
      <a-form-item field="name" label="名称" :rules="rules.name">
        <a-input v-model="propValForm.name" placeholder="请输入名称" allow-clear />
      </a-form-item>
      <a-form-item field="slug" label="标识" :rules="rules.slug">
        <a-input v-model="propValForm.slug" placeholder="请输入标识" allow-clear />
      </a-form-item>
    </a-form>
    <template #footer class="modal-footer">
      <a-button @click="showAddPropVal = false">取消</a-button>
      <a-button type="primary" :loading="loading" @click="submitPropVal">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, computed, onMounted } from 'vue'
  import { batchAttribute, getRelatedList, batchAttributeTerm, attributeBatchCreateOrUpdateSkipNullById } from '@/api/product'
  import { cloneDeep } from 'lodash-es'
  import { Message } from '@arco-design/web-vue'

  let props = defineProps(['modelValue', 'type', 'info', 'shopId'])
  let emits = defineEmits(['save', 'update:modelValue'])
  const pageInfo = ref({
    total: 0,
    pageSize: 50,
    pageNum: 1,
  })
  const formRef = ref()
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })
  let form = ref<any>({
    name: '',
    slug: '',
    description: '',
    erpAttrId: '',
  })
  let loading = ref(false)
  let relatedList: any = ref([])
  let delIds = ref<Array<string>>([])
  let propertyValueList: any = ref([{ name: '', slug: '' }])
  let allPropertyValueList: Array<any> = []
  let filterPropertyValueList: Array<any> = []

  let rules = ref({
    name: [{ required: true, message: '请输入' }],
    slug: [{ required: true, message: '请输入' }],
  })

  const showAddPropVal = ref(false)
  const addPropValType = ref('add')
  const propValForm = ref<any>({})
  const propValFormRef = ref()
  let propValData: any = {}
  const selectIds = ref<Array<string>>([])
  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const searchVal = ref()

  // 打开添加属性项弹窗
  const openPropValDialog = (type: string, item?: any) => {
    addPropValType.value = type
    propValForm.value = {
      name: item?.name,
      slug: item?.slug,
      id: item?.id,
    }
    propValData = item || {}
    showAddPropVal.value = true
  }
  // 添加、更新属性值
  const submitPropVal = async () => {
    const valid = await propValFormRef.value.validate()
    if (valid) return
    let params: any = {
      param: {},
      productAttributeId: form.value.id,
      shopId: props.shopId,
    }
    if (addPropValType.value == 'add') {
      params.param.create = [
        {
          name: propValForm.value.name.trim(),
          slug: propValForm.value.slug.trim(),
        },
      ]
    } else {
      params.param.update = [
        {
          name: propValForm.value.name,
          slug: propValForm.value.slug,
          id: propValForm.value.id,
        },
      ]
    }
    const res: any = await batchAttributeTerm(params)
    if (res) {
      if (addPropValType.value == 'add') {
        Message.success('创建成功，当前操作不是立即生效，请等待几分钟后刷新页面')
        // allPropertyValueList.unshift({
        //   name: propValForm.value.name,
        //   slug: propValForm.value.slug,
        // })
      } else {
        Message.success('更新成功，当前操作不是立即生效，请等待几分钟后刷新页面')
        // propValData.name = propValForm.value.name
        // propValData.slug = propValForm.value.slug
      }
      // changeAllPropertyValueList()
      showAddPropVal.value = false
    }
  }
  // 删除属性值
  const deletePropVal = async (ids: Array<string>) => {
    if (!ids.length) {
      Message.error('请选择需要删除的属性')
      return
    }
    let params: any = {
      param: {
        delete: ids,
      },
      productAttributeId: form.value.id,
      shopId: props.shopId,
    }
    const res: any = await batchAttributeTerm(params)
    if (res) {
      Message.success('删除成功，当前操作不是立即生效，请等待几分钟后刷新页面')
    }
  }
  // 分页
  const changePage = (val: number) => {
    pageInfo.value.pageNum = val
    setTableList()
  }
  const sizeChange = (val?: number) => {
    pageInfo.value.pageNum = 1
    pageInfo.value.pageSize = val || pageInfo.value.pageSize
    setTableList()
  }
  const setTableList = () => {
    let pageNum = pageInfo.value.pageNum
    let pageSize = pageInfo.value.pageSize
    propertyValueList.value = filterPropertyValueList.slice((pageNum - 1) * pageSize, pageNum * pageSize)
  }

  // 获取属性
  const getRelated = async () => {
    let params = {
      pageSize: 9999999,
    }
    const res: any = await getRelatedList(params)
    relatedList.value = res.data?.records || []
  }

  // 切换erp属性映射
  const selErpAttr = (id: any) => {
    let item = relatedList.value.find((item: any) => item.id === id)
    let arr = item?.propValueList || []
    let newAddArr: any = []
    arr.forEach((e: any) => {
      let obj = {
        name: e.propValue,
        slug: e.propValueEn,
      }
      let index = allPropertyValueList.findIndex((item: any) => item.name == e.propValue)
      if (index == -1) {
        allPropertyValueList.push(obj)
        newAddArr.push(obj)
      }
    })

    // 将属性值重新存一份
    if (newAddArr[0]) setData(allPropertyValueList)

    if (allPropertyValueList[0].name == '') allPropertyValueList.splice(0, 1)
    changeAllPropertyValueList()
  }

  const setData = async (data: any) => {
    let params = {
      param: {
        create: data,
      },
      productAttributeId: form.value.id,
      shopId: props.shopId,
    }

    const res: any = await batchAttributeTerm(params)
    if (res) {
      Message.success('新增成功')
    }
  }

  const changeAllPropertyValueList = () => {
    pageInfo.value.pageNum = 1
    if (!searchVal.value) {
      filterPropertyValueList = cloneDeep(allPropertyValueList)
    } else {
      filterPropertyValueList = allPropertyValueList.filter((el: any) => {
        return el.name?.indexOf(searchVal.value) > -1 || el.slug?.indexOf(searchVal.value) > -1
      })
    }
    pageInfo.value.total = filterPropertyValueList.length
    setTableList()
  }
  const selectColumn = (val: any) => {
    selectIds.value = val
  }

  const submit = async () => {
    const valid = await formRef.value.validate()
    if (valid) return

    let params: any = {
      param: {},
      shopId: props.shopId,
    }
    if (props.type == 'add') {
      let obj = {
        ...form.value,
      }
      obj.name = obj.name.trim()
      obj.slug = obj.slug.trim()
      params.param.create = [obj]
    } else {
      let obj = {
        ...form.value,
      }
      obj.name = obj.name.trim()
      obj.slug = obj.slug.trim()
      params.param.update = [obj]
    }

    try {
      loading.value = true
      const res: any = await batchAttribute(params)
      // // 编辑的时候添加属性值
      // if (props.type == 'edit') await setPropertyValue()
      // 保存属性值
      if (form.value.erpAttrId) {
        for (let index = 0; index < allPropertyValueList.length; index++) {
          let item = allPropertyValueList[index]
          if (item.name == '' || item.slug == '') {
            loading.value = false
            return Message.error('请完善属性值信息')
          }
        }
        await saveErpProperty()
      }

      if (res) {
        Message.success(props.type == 'add' ? '新增成功。当前操作不是立即生效，请等待几分钟后刷新页面' : '编辑成功。当前操作不是立即生效，请等待几分钟后刷新页面')
        emits('save')
        showvisible.value = false
      }
    } catch (error) {}
    loading.value = false
  }

  const getErpAttrName = () => {
    let item = relatedList.value.find((item: any) => item.id === form.value.erpAttrId)
    return item.name
  }
  // 保存erp映射属性
  const saveErpProperty = async () => {
    let params = {
      createOrUpdateDocList: [
        {
          id: props.info.id,
          prop: {
            id: form.value.erpAttrId,
            name: getErpAttrName(),
          },
        },
      ],
    }
    await attributeBatchCreateOrUpdateSkipNullById(params)
  }
  const init = () => {
    let editPropertyValue = props.info?.termList || []
    // 回显属性基本信息
    let obj = {
      id: props.info.dataFromRestApi.id,
      name: props.info.dataFromRestApi.name,
      slug: props.info.dataFromRestApi.slug,
      description: props.info.dataFromRestApi.slug,
      erpAttrId: props.info.prop?.id || '',
    }
    form.value = obj

    // 回显属性值信息
    editPropertyValue.forEach((e: any) => {
      let obj = {
        name: e.dataFromRestApi.name,
        slug: e.dataFromRestApi.slug,
        id: e.dataFromRestApi.id,
      }
      allPropertyValueList.push(obj)
      if (allPropertyValueList[0].name == '') allPropertyValueList.splice(0, 1)
    })
    changeAllPropertyValueList()
  }
  // const delPropertyValueList = (info: any, rowIndex: number) => {
  //   delIds.value.push(info.id)
  //   propertyValueList.value.splice(rowIndex, 1)
  // }

  // const addItem = (i: number) => {
  //   let obj = {
  //     name: '',
  //     slug: '',
  //     isEdit: true,
  //   }
  //   propertyValueList.value.splice(i + 1, 0, obj)
  // }

  // // 设置属性值
  // const setPropertyValue = async () => {
  //   let params: any = {
  //     param: {
  //       create: [],
  //       update: [],
  //       delete: delIds.value,
  //     },
  //     productAttributeId: form.value.id,
  //     shopId: props.shopId,
  //   }
  //   // 处理不同类型的数据 新增 编辑 删除
  //   propertyValueList.value.forEach((item: any) => {
  //     let obj: any = {}
  //     if (item.id) {
  //       obj.id = item.id
  //       obj.name = item.name
  //       obj.slug = item.slug
  //       params.param.update.push(obj)
  //     } else {
  //       obj.name = item.name
  //       obj.slug = item.slug
  //       params.param.create.push(obj)
  //     }
  //   })

  //   const res: any = await batchAttributeTerm(params)
  // }

  onMounted(() => {
    getRelated()
    if (props.type == 'edit') init()
  })
</script>

<style lang="less" scoped>
  .ft20 {
    font-size: 20px;
  }
  .table-wrap {
    margin-left: 20px;
    width: 700px;
    height: calc(84vh - 120px);
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
</style>
